package com.buptsse.queryresults;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.buptsse.queryresults.bean.SubjectInfo;
import com.buptsse.queryresults.bean.SummaryInfo;
import com.buptsse.queryresults.bean.UserInfo;
import com.buptsse.queryresults.utils.NetUtils;
import com.buptsse.queryresults.utils.Utils;
import com.buptsse.queryresults.widgets.SummaryListAdapter;
import com.buptsse.queryresults.widgets.SummaryListItemView;
import com.umeng.analytics.MobclickAgent;

public class MainActivity extends Activity implements OnClickListener{

	private static final int MSG_SHOW_SIMPLE_RESULT = 1000;
	private static final int MSG_SHOW_MULTI_RESULT = 2000;
	private static final int MSG_SHOW_RESULT_FAILD = 4000;
	private static final int MSG_SHOW_SAVE_ID = 1002;

	private Context mContext; 
	
	private ProgressDialog mProgressDialog;
	private EditText mEditId;
	private Button mBtnSubmit;
	private TextView mTxtResult;
	private ListView mListMultiResult;
	private LinearLayout mLayoutMultiResult;

	private ExecutorService mThreadPool;
	private UserInfo mUserInfo;
	private SummaryInfo mSummaryInfo;
	private ArrayList<SubjectInfo> mSubjectList = new ArrayList<SubjectInfo>();
	
	Handler mHandler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case MSG_SHOW_MULTI_RESULT:
				mProgressDialog.dismiss();
				showMultiResult();
				break;
			case MSG_SHOW_SIMPLE_RESULT:
				mProgressDialog.dismiss();
				mLayoutMultiResult.setVisibility(View.GONE);
				mTxtResult.setVisibility(View.VISIBLE);
				mTxtResult.setText((String) msg.obj);
				break;
			case MSG_SHOW_RESULT_FAILD:
				mProgressDialog.dismiss();
				mLayoutMultiResult.setVisibility(View.GONE);
				mTxtResult.setVisibility(View.VISIBLE);
				mTxtResult.setText(R.string.exception_alert);
				break;
			case MSG_SHOW_SAVE_ID:
				mEditId.setText((String) msg.obj);
				break;
			default:
				break;
			}
			super.dispatchMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		mThreadPool = Executors.newSingleThreadExecutor(); 
//		MobclickAgent.setDebugMode( true );
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	private void initView() {
		
		//------------Init UI View---------------------------//
		mEditId = (EditText) findViewById(R.id.main_id_edit);
		mBtnSubmit = (Button) findViewById(R.id.main_sumbit);
		mTxtResult = (TextView) findViewById(R.id.main_results);
		mListMultiResult = (ListView) findViewById(R.id.main_multi_results);
		mLayoutMultiResult = (LinearLayout)findViewById(R.id.main_multi);
		mProgressDialog = new ProgressDialog(mContext);
		mHeadView = new SummaryListItemView(mContext);
		//------------Regist Event----------------------------//
		mBtnSubmit.setOnClickListener(this);
		
		//------------Read And Show Cache--------------------//
		showCacheID();
	}

	private void requestResult(final String id) {
		
		mThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String raw = NetUtils.downloadResultHtml(id);
				if(TextUtils.isEmpty(raw)){
					mHandler.sendEmptyMessage(MSG_SHOW_RESULT_FAILD);
				}else{
					String result = Utils.getInfo(raw);
					if (TextUtils.isEmpty(result)) {
						mHandler.sendEmptyMessage(MSG_SHOW_RESULT_FAILD);
					} else {
						formatResponseData(result);
					}
				}
			}
		});
	}
	
	private SummaryListItemView mHeadView = null;
	private void showMultiResult(){
		//TODO
		mTxtResult.setVisibility(View.GONE);
		mLayoutMultiResult.setVisibility(View.VISIBLE);
		if(mHeadView != null){
			mListMultiResult.removeHeaderView(mHeadView);
		}
		mHeadView.setTitleText(mUserInfo.getUserName()+" ("+mUserInfo.getUserID()+")");
		Drawable mGenderIcon = null;
		if(mUserInfo.getUserSex().equals("女")){
			mGenderIcon = this.getResources().getDrawable(R.drawable.widget_gender_woman);
		}else{
			mGenderIcon = this.getResources().getDrawable(R.drawable.widget_gender_man);
		}
		if(null != mGenderIcon){
			((TextView)mHeadView.getChildAt(0)).setCompoundDrawablesWithIntrinsicBounds(mGenderIcon, null, null, null);
		}
		mListMultiResult.addHeaderView(mHeadView);
		mListMultiResult.setAdapter(new SummaryListAdapter(mSummaryInfo, mContext));
	}
	
	private void formatResponseData(final String rawStr){
		
		mThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String[] datas = rawStr.split("\r\n");
				Message msg = new Message();
				
				if(datas.length > 1){
					mUserInfo = new UserInfo(datas[0]);
					mSubjectList.clear();
					for(int i = 1 ; i<datas.length; i++){
						mSubjectList.add(new SubjectInfo(datas[i]));
					}
					mSubjectList.trimToSize();
					mSummaryInfo = new SummaryInfo(mSubjectList);
					if (checkDataLoadSuccess()) {
						msg.what = MSG_SHOW_MULTI_RESULT;
						mHandler.sendMessage(msg);
						return;
					}
				} 
				msg.obj = rawStr;
				msg.what = MSG_SHOW_SIMPLE_RESULT;
				mHandler.sendMessage(msg);
			}
		});
	}
	
	private boolean checkDataLoadSuccess(){
		if(null != mUserInfo && null != mSummaryInfo && !mSubjectList.isEmpty()){
			return true;
		}
		return false;
	}
	
	private void showCacheID(){
		
		mThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String id = Utils.getID(mContext);
				if(!TextUtils.isEmpty(id)){
					Message msg = new Message();
					msg.what = MSG_SHOW_SAVE_ID;
					msg.obj = id;
					mHandler.sendMessage(msg);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_sumbit:
			/***** check edit *****/
			String id = Utils.checkEdit(mContext, mEditId.getText().toString());
			if (!TextUtils.isEmpty(id)) {
				/***** check network *****/
				if (NetUtils.isNetworkConnected(mContext)) {
					/***** hide input keybroad *****/
					((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
							.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus()
									.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
					/***** save id *****/
					Utils.saveID(mContext, id); 
					/***** show loadding *****/
					mProgressDialog.setMessage(getString(R.string.querying_please_wait));
					mProgressDialog.show();
					/***** send net request *****/
					requestResult(id);
					MobclickAgent.onEvent( mContext, "query", id);
				} else {
					Toast.makeText(mContext, R.string.no_net_connection,Toast.LENGTH_LONG).show();
				}
			}
			break;

		default:
			break;
		}
	}

}
